#import "MxhLocationPlugin.h"
#import <CoreLocation/CoreLocation.h>
#import "LocationTool.h"

@interface MxhLocationPlugin ()<FlutterStreamHandler>

//定位工具对象
@property (nonatomic, strong) LocationTool * loc;
//经纬度
@property (nonatomic, strong) NSString * locationStr;

//可以在任意位置回传值 self.result(msg);
//@property (nonatomic, strong) FlutterResult result;

//数据流载体
@property (nonatomic, strong) FlutterEventSink eventSink;

@end

@implementation MxhLocationPlugin

//工厂模式
+ (instancetype)sharedInstance {
    static MxhLocationPlugin *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

//注册 methodChannel 及 eventChannel
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"mxh_location"
            binaryMessenger:[registrar messenger]];
  MxhLocationPlugin * instance = [MxhLocationPlugin sharedInstance];
  [registrar addMethodCallDelegate:instance channel:channel];
    FlutterEventChannel* eventChannel = [FlutterEventChannel eventChannelWithName:@"mxh_location_event" binaryMessenger:[registrar messenger]];
  [eventChannel setStreamHandler:instance];
}

//监听chanel函数
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSArray * methods = [NSArray arrayWithObjects:
                         @"getPlatformVersion",
                         @"startLocation",
                         @"stopLocation",
                         nil];
    NSInteger index = [methods indexOfObject:call.method];
    switch (index) {
        case 0:
            result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
            break;
        case 1:
            //开始定位
//            self.result = result;
            [self startLocation];
            break;
        case 2:
            //结束定位
            [_loc stopLocation];
            break;
        default:
            result(FlutterMethodNotImplemented);
            break;
    }
}

//开始定位
- (void)startLocation {
    _loc = [[LocationTool alloc] init];
    [_loc startLocation];
    __weak typeof(self) weakSelf = self;
    _loc.currentLocation = ^(NSString * latitude, NSString * longitude) {
        NSString * locationStr = [NSString stringWithFormat:@"%@-%@", latitude, longitude];
        [weakSelf sendMessageForFlutter:locationStr];
    };
}

//向原生flutter发送消息
- (void)sendMessageForFlutter:(NSString* )msg {
    if (self.eventSink) {
        //NSLog(@"iOS持续获取经纬度：%@", msg);
        self.eventSink(msg);
    } else {
        NSLog(@"error");
    }
//    self.result(msg);
}

/// flutter不再接收
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
    // arguments flutter给native的参数
    self.eventSink = nil;
    return nil;
}

//这个onListen是Flutter端开始监听这个channel时的回调，第二个参数 EventSink是用来传数据的载体
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(FlutterEventSink)eventSink {
    // arguments flutter给native的参数
    // 回调给flutter， 建议使用实例指向，因为该block可以使用多次
    self.eventSink = eventSink;
    return nil;
}

@end
